import { config } from './shared/smartadmin.config'

class AppInit {
  resourceList: any[] = []
  routerUrlList: any = []
  paramsObj:any={}

  public constructor() {}
  initApp() {
    return new Promise((resolve, reject) => {
      let currentUrl = window.location.search
      if (currentUrl.includes('token')) {
        console.log(this.getParams())
        this.paramsObj = this.getParams()
        const token = this.paramsObj['token'] || ''
        const page = this.paramsObj['page'] || ''
        if (token && page) {
          localStorage.clear()
          localStorage.setItem('token', token)
          common.clearCookie()
          common.setCookie('isLogin', 'true', 8) //登录前端设置8小时失效
          common.setCookie('isFirst', 'true')
          //读取菜单数据
          this.initMenu()
            .then(() => {
              resolve(true)
            })
            .catch(() => {
              localStorage.clear()
              common.clearCookie()
              resolve(true)
            })
        } else {
          resolve(true)
        }
      } else {
        resolve(true)
      }
    })
  }
  // 拉取菜单数据,对resourceList数据进行整合,最多支持4级菜单
  initMenu() {
    return new Promise((resolve, reject) => {
      axios
        .post(config.BaseURL + 'index2.html', {}, { headers: { 'X-Token': localStorage.getItem('token') || '' } })
        .then(res => {
          const data = res.data
          this.resourceList = []
          this.routerUrlList = []
          if (data.success) {
            var tempArr = data.data.menu
            if (!tempArr || tempArr.length == 0) {
              console.log('您没有权限访问!')
              reject()
              return
            }

            const parseMenu = (arr: any[]): any[] => {
              let map = {}
              arr.forEach(i => {
                map[i.id] = i
              })

              let treeData = []
              arr.forEach(child => {
                child.btnArr = []
                if (child.path && child.type === 0) {
                  this.routerUrlList.push(child.path)
                }
                // 判断当前数据的parentId是否存在map中
                const mapItem = map[child.parentId]

                if (mapItem) {
                  // 存在则表示当前数据不是最顶层数据
                  if (child.type === 1) {
                    ;(mapItem.btnArr || (mapItem.btnArr = [])).push(child)
                  } else {
                    ;(mapItem.children || (mapItem.children = [])).push(child)
                  }
                } else {
                  // 不存在则是顶层数据
                  treeData.push(child)
                }
              })
              return treeData
            }

            const formatData = (data: any): string => {
              return encodeURIComponent(JSON.stringify(data))
            }

            this.resourceList = parseMenu(tempArr)
            localStorage.removeItem('s-menu-url')
            localStorage.setItem('s-menu-url', formatData(this.routerUrlList)) //菜单缓存到本地
            const isHome: boolean = !this.resourceList[0].children.length && this.resourceList[0].path
            const isOrdinaryMenu: boolean =
              this.resourceList[0].children.length && this.resourceList[0].children[0].path
            if (isHome || isOrdinaryMenu) {
              localStorage.removeItem('s-menu')
              localStorage.setItem('s-menu', formatData(this.resourceList)) //菜单缓存到本地
              localStorage.setItem(
                isHome ? 'cargpsw_desktop' : `cargpsw_${this.resourceList[0].children[0].sourceKey}`,
                isHome ? formatData(this.resourceList[0].btnArr) : formatData(this.resourceList[0].children[0].btnArr)
              )
              // this.router.navigate([isHome ? this.resourceList[0].path : this.resourceList[0].children[0].path]) //默认跳转第一条数据菜单,没有子菜单情况下,跳转父级
              const page = this.paramsObj.page || ''
              if(this.paramsObj.token) delete this.paramsObj.token
              if(this.paramsObj.page) delete this.paramsObj.page
              const paramsObjCopy = JSON.stringify(this.paramsObj)
              if(paramsObjCopy !== '{}'){
                localStorage.setItem('paramsObj', paramsObjCopy) //除token和page外，额外参数缓存到本地
              }
              console.log(this.paramsObj)
              window.location.replace(window.location.href.split('?')[0] + '#' + page)
              resolve(true)
            } else {
              console.log('您没有权限访问!')
              reject()
            }
          } else {
            reject()
          }
        })
        .catch(() => {
          reject()
        })
    })
  }
  getParams() {
    var result = {} // 定义一个全局的对象
    var str = window.location.search
    if (str.startsWith('?')) {
      // 判断str以？开头的
      var strParams = str.split('?')[1]
      var arrParams = strParams.split('&')
      //然后进行for循环，这里直接用了forEach
      arrParams.forEach(item => {
        var temKey = item.split('=')[0]
        var temVal = item.split('=')[1]
        result[temKey] = temVal
      })
    }
    return result
  }
}

export const appInit = new AppInit()
